package admin_user

import (
	"context"
	adminUserApi "go-skeleton/api/admin/service/admin_user"
	"go-skeleton/app/admin/service/internal/biz"
	"google.golang.org/protobuf/types/known/emptypb"
)

type AdminUserService struct {
	adminUserApi.UnimplementedAdminUserServiceServer

	uc *biz.AdminUserBiz
}

func NewAdminUserService(uc *biz.AdminUserBiz) *AdminUserService {
	return &AdminUserService{uc: uc}
}

func (s *AdminUserService) Captcha(ctx context.Context, req *emptypb.Empty) (resp *adminUserApi.CaptchaReply, err error) {
	resp = &adminUserApi.CaptchaReply{}
	id, b64s, err := s.uc.Captcha(ctx)
	if err != nil {
		return
	}
	resp.CaptchaId = id
	resp.CaptchaImage = b64s
	return
}

func (s *AdminUserService) Login(ctx context.Context, in *adminUserApi.LoginRequest) (resp *adminUserApi.LoginReply, err error) {
	return s.uc.Login(ctx, in)
}

func (s *AdminUserService) SendCode(ctx context.Context, in *adminUserApi.SendCodeRequest) (resp *emptypb.Empty, err error) {
	err = s.uc.SendCode(ctx, in.Phone)
	return
}

func (s *AdminUserService) GetAdminLoginUserInfo(ctx context.Context, req *emptypb.Empty) (resp *adminUserApi.AdminUserInfoReply, err error) {
	resp = &adminUserApi.AdminUserInfoReply{}
	ctxUserId := ctx.Value("user_id").(int64)
	user, err := s.uc.FindByID(ctx, ctxUserId)
	if err != nil {
		return
	}

	userInfo, err := s.uc.ReturnUserInfo(ctx, user)
	if err != nil {
		return
	}

	resp = &adminUserApi.AdminUserInfoReply{
		UserInfo: userInfo,
	}
	return
}

func (s *AdminUserService) GetAdminUserInfo(ctx context.Context, in *adminUserApi.GetAdminUserInfoRequest) (resp *adminUserApi.AdminUserInfoReply, err error) {
	resp = &adminUserApi.AdminUserInfoReply{}
	user, err := s.uc.FindByID(ctx, in.Id)
	if err != nil {
		return
	}

	resp = &adminUserApi.AdminUserInfoReply{
		UserInfo: &adminUserApi.UserInfo{
			Id:       user.ID,
			NickName: user.NickName,
			Avatar:   user.Avatar,
		},
	}
	return
}

func (s *AdminUserService) GetAdminUserList(ctx context.Context, req *adminUserApi.GetAdminUserListRequest) (resp *adminUserApi.GetAdminUserListReply, err error) {
	return s.uc.List(ctx, req)
}

func (s *AdminUserService) AddUser(ctx context.Context, req *adminUserApi.UserInfo) (resp *adminUserApi.UserInfo, err error) {
	return s.uc.Save(ctx, req)
}

func (s *AdminUserService) EditUser(ctx context.Context, req *adminUserApi.UserInfo) (resp *adminUserApi.UserInfo, err error) {
	return s.uc.Update(ctx, req)
}

func (s *AdminUserService) DelUser(ctx context.Context, req *adminUserApi.UserInfo) (resp *emptypb.Empty, err error) {
	return s.uc.Del(ctx, req.Id)
}
